<template>
  <view class="template-topic tn-safe-area-inset-bottom">
    <!-- 顶部自定义导航 -->
    <tn-nav-bar backgroundColor="#1c1d20" @click="goBack" style="color: #fff;">创建角色</tn-nav-bar>

    <!-- <canvas canvas-id="star_canvas" class="mycanvas" :style="'width:' + screenWidth + 'px;height:' + screenHeight + 'px;'"></canvas> -->

    <view class="topic" :style="{ paddingTop: vuex_custom_bar_height + 'px' }">
      <!-- 输入框内容-->
	  
	  <view class="input-box">
	    <!-- 问题 -->
	    <block>
	      <!-- <view class="tn-text"> -->
	        <image src="/static/META.png" style="width: 100%; border-radius: 30rpx;"></image>
	      <!-- </view> -->
	    </block>
	  </view>
	  
	  <view class="input-box">
	    <block>
	      <view class="tn-text">
	        设置智能体形象
	      </view>
	  
	      <view class="tn-flex tn-flex-row-between tn-flex-col-center tn-margin">
	        <view class="justify-content-item tn-text-df tn-color-grey" @tap="clear">
	          <text class="tn-padding-xs">清空上传</text>
	          <text class="tn-icon-delete"></text>
	        </view>
	      </view>
	  
	      <view class="tn-margin-left tn-padding-top-xs">
	        <tn-image-upload-drag ref="imageUpload" :action="action" :width="200" :height="200" @on-success="handleSuccess" @error="handleError"/>
	  
	      </view>
	    </block>
	  </view>

      <!-- <view class="input-box input-box-padding">
        <block>
          <view class="tn-text1">
            我的角色库
          </view>
      
          <view class="select-content">
            <view class="select-content-item" v-for="item in typeList" :key="item.id"
              :class="{ 'select-content-item-active': item.id == currentIndex }" @tap="onSelectType(item.id)">
              {{ item.name }}
            </view>
          </view>
      

        </block>
      </view> -->

    </view>
	
	<!--语音-->
	<my-voice v-show="showVoice"></my-voice>

    <view class="bottom-box">
      <view style="position: relative; left: 5%;margin-top: 20px;">
        <tn-button shape="round" backgroundColor="#FBE6B1" padding="40rpx 0" width="90%" :fontSize="32" fontBold
		  @click="submit">
          <text class="tn-color-grey-dark">创建角色   -1000</text>
		  <text class="tn-icon-money tn-padding-left-xs tn-color-black"></text>
        </tn-button>
      </view>
    </view>
  </view>
</template>

<script>
import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
import myVoice from '@/components/self-voice/index.vue'

const Point = class {
  constructor(x, y) {
    this.x = x
    this.y = y
    this.r = 1 + Math.random() * 2
    this.sx = Math.random() * 2 - 1
    this.sy = Math.random() * 2 - 1
  }

  draw(ctx) {
    ctx.beginPath()
    ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI)
    ctx.closePath()
    ctx.fillStyle = '#fff'
    ctx.fill()
  }

  move(w, h) {
    this.x += this.sx
    this.y += this.sy
    if (this.x > w || this.x < 0) this.sx = -this.sx
    if (this.y > h || this.y < 0) this.sy = -this.sy
  }

  drawLine(ctx, p) {
    const dx = this.x - p.x
    const dy = this.y - p.y
    const d = Math.sqrt(dx * dx + dy * dy)
    if (d < 100) {
      var alpha = (100 - d) / 300 * 1
      ctx.beginPath()
      ctx.moveTo(this.x, this.y)
      ctx.lineTo(p.x, p.y)
      ctx.closePath()
      ctx.strokeStyle = 'rgba(255, 255, 255, ' + alpha + ')'
      ctx.strokeWidth = 1
      ctx.stroke()
    }
  }
}

const sysinfo = uni.getSystemInfoSync()
const w = 400
const h = 1000
const recorderManager = uni.getRecorderManager()


export default {
  name: 'TemplateTopic',
  mixins: [template_page_mixin],
  components: { myVoice },
  data() {
    return {
      // 当前选中的模式
      currentModeIndex: 0,
      // 粒子
      ctx: null,
      screenWidth: sysinfo.screenWidth,
      screenHeight: sysinfo.screenHeight,
      timer: null,
      points: [],
      action: 'https://tk.cycyai.com:6501/api/core/user/uploadi',
      sexList: ['请选择性别', '男', '女'],
      timbreName: ['请选择音色', '爽快思思/Skye', '温暖阿虎/Alvin', '少年梓辛/Brayan', '邻家女孩', '渊博小叔', '阳光青年',
        '甜美小源', '清澈梓梓', '解说小明', '开朗姐姐', '邻家男孩', '甜美悦悦', '心灵鸡汤', '京腔侃爷/Harmony', '湾湾小何', '湾区大叔', '呆萌川妹', '广州德哥',
        '北京小爷', '浩宇小哥', '广西远舟', '妹坨洁儿', '豫州子轩', '高冷御姐', '傲娇霸总', '魅力女友', '深夜播客', '柔美女友', '撒娇学妹', '病弱少女',
        '活泼女孩', '和蔼奶奶', '邻居阿姨', '温柔小雅', '东方浩然'],
      roleList: ['请选择性格', '鲁迅', '潘金莲', '舔狗男', '舔狗女', '高冷御姐', '霸道总裁'],
      role: ['', 'LuXun', 'PanJinLian', 'TianGouNan', 'TianGouNv', 'GaoLengYuJie', 'BaDaoZongCai'],
      timbre: [{
        id: 0,
        name: '',
        type: '',
      }, {
        id: 1,
        name: '爽快思思/Skye',
        type: 'zh_female_shuangkuaisisi_moon_bigtts',
      }, {
        id: 2,
        name: '温暖阿虎/Alvin',
        type: 'zh_male_wennuanahu_moon_bigtts',
      }, {
        id: 3,
        name: '少年梓辛/Brayan',
        type: 'zh_male_shaonianzixin_moon_bigtts',
      }, {
        id: 4,
        name: '邻家女孩',
        type: 'zh_female_linjianvhai_moon_bigtts',
      }, {
        id: 5,
        name: '渊博小叔',
        type: 'zh_male_yuanboxiaoshu_moon_bigtts',
      }, {
        id: 6,
        name: '阳光青年',
        type: 'zh_male_yangguangqingnian_moon_bigtts',
      }, {
        id: 7,
        name: '甜美小源',
        type: 'zh_female_tianmeixiaoyuan_moon_bigtts',
      }, {
        id: 8,
        name: '清澈梓梓',
        type: 'zh_female_qingchezizi_moon_bigtts',
      }, {
        id: 9,
        name: '解说小明',
        type: 'zh_male_jieshuoxiaoming_moon_bigtts',
      }, {
        id: 10,
        name: '开朗姐姐',
        type: 'zh_female_kailangjiejie_moon_bigtts',
      }, {
        id: 11,
        name: '邻家男孩',
        type: 'zh_male_linjiananhai_moon_bigtts',
      }, {
        id: 12,
        name: '甜美悦悦',
        type: 'zh_female_tianmeiyueyue_moon_bigtts',
      }, {
        id: 13,
        name: '心灵鸡汤',
        type: 'zh_female_xinlingjitang_moon_bigtts',
      }, {
        id: 14,
        name: '京腔侃爷/Harmony',
        type: 'zh_male_jingqiangkanye_moon_bigtts',
      }, {
        id: 15,
        name: '湾湾小何',
        type: 'zh_female_wanwanxiaohe_moon_bigtts',
      }, {
        id: 16,
        name: '湾区大叔',
        type: 'zh_female_wanqudashu_moon_bigtts',
      }, {
        id: 17,
        name: '呆萌川妹',
        type: 'zh_female_daimengchuanmei_moon_bigtts',
      }, {
        id: 18,
        name: '广州德哥',
        type: 'zh_male_guozhoudege_moon_bigtts',
      }, {
        id: 19,
        name: '北京小爷',
        type: 'zh_male_beijingxiaoye_moon_bigtts',
      }, {
        id: 20,
        name: '浩宇小哥',
        type: 'zh_male_haoyuxiaoge_moon_bigtts',
      }, {
        id: 21,
        name: '广西远舟',
        type: 'zh_male_guangxiyuanzhou_moon_bigtts',
      }, {
        id: 22,
        name: '妹坨洁儿',
        type: 'zh_female_meituojieer_moon_bigtts',
      }, {
        id: 23,
        name: '豫州子轩',
        type: 'zh_male_yuzhouzixuan_moon_bigtts',
      }, {
        id: 24,
        name: '高冷御姐',
        type: 'zh_female_gaolengyujie_moon_bigtts',
      }, {
        id: 25,
        name: '傲娇霸总',
        type: 'zh_male_aojiaobazong_moon_bigtts',
      }, {
        id: 26,
        name: '魅力女友',
        type: 'zh_female_meilinvyou_moon_bigtts',
      }, {
        id: 27,
        name: '深夜播客',
        type: 'zh_male_shenyeboke_moon_bigtts',
      }, {
        id: 28,
        name: '柔美女友',
        type: 'zh_female_sajiaonvyou_moon_bigtts',
      }, {
        id: 29,
        name: '撒娇学妹',
        type: 'zh_female_yuanqinvyou_moon_bigtts',
      }, {
        id: 30,
        name: '病弱少女',
        type: 'ICL_zh_female_bingruoshaonv_tob',
      }, {
        id: 31,
        name: '活泼女孩',
        type: 'ICL_zh_female_huoponvhai_tob',
      }, {
        id: 32,
        name: '和蔼奶奶',
        type: 'ICL_zh_female_heainainai_tob',
      }, {
        id: 33,
        name: '邻居阿姨',
        type: 'ICL_zh_female_linjuayi_tob',
      }, {
        id: 34,
        name: '温柔小雅',
        type: 'zh_female_wenrouxiaoya_moon_bigtts',
      }, {
        id: 35,
        name: '东方浩然',
        type: 'zh_male_dongfanghaoran_moon_bigtts',
      }],
      makeNewAvatar: {
        name: '',
        info: '',
        avatarImg: '',
        timbreName: '请选择音色',
        timbre: '',
        sex: '请选择性别',
        roleName: '请选择性格',
        role: ''
      },
      typeList: [{
        id: "1",
        name: "男",
      }, {
        id: "2",
        name: "女",
      }, {
        id: "3",
        name: "其他",
      }],
      mTokenInfo: '',
      currentIndex: 0,
	  showVoice: false,
	  uploadUrl: ''
    }
  },
  onLoad(options) {
    this.from = options.from || ''

    for (let i = 0; i < 80; i++) {
      this.points.push(new Point(Math.random() * w, Math.random() * h))
    }
    this.ctx = uni.createCanvasContext('star_canvas')
    // console.log(points)
	recorderManager.onError((err) => {
	  console.error('recorderManager：'+err)
	  // 根据错误信息进行相应的处理
	})
	
	// 结束录音
	recorderManager.onStop(function async(res) {
	      // date.path = res.tempFilePath  // 这个是录音文件的临时地址
	      // date.time = timeLength.value    // 录音时长
	       
	         // 上传音频文件到服务器上
	        uni.uploadFile({
		     url: 'https://tk.cycyai.com:6501/api/core/user/uploadcopy', //仅为示例，非真实的接口地址
		     filePath: res.tempFilePath, //  这个是录音文件的临时地址
		     name: 'file',
		     formData: {
				   'user': 'test'
				},
		     success: (uploadFileRes) => {
				console.log('uploadFileRes' +uploadFileRes.data)
		      }
		});
	       console.log('recorder stop' + JSON.stringify(res))
	        self.voicePath = res.tempFilePath
	})

    this.gameloop() //进行
    // this.ctx.setFillStyle('red')
    // this.ctx.fillRect(200, 300, 50, 50)
    // this.ctx.draw()
  },
  onUnload() {
    clearTimeout(this.timer)
  },

  methods: {
	handleSuccess(event) {
      // 处理上传成功逻辑
      console.log('上传成功', event);
	  this.uploadUrl = event.data.uploadUrl;
    },
	handleError(err) {
		// 上传失败后的处理逻辑
		console.error('上传失败', err);
	},
    onSelectType(id) {
      this.currentIndex = id;
    },
    submit() {
	  if (this.uploadUrl == '') {
	    uni.showToast({
	      title: '请先上传符合要求的图片',
	      icon: 'none',
	      duration: 1000
	    })
	    return
	  }
      uni.setStorageSync('makeNewAvatar', this.makeNewAvatar)
      this.$Request.getT("/api/core/user/mtoken").then(async (res) => {
        if (res.code == 20000) {
          // console.log("nextCas");
          this.mTokenInfo = res.data.masterTokenInfo;
		  uni.setStorageSync('mToken', res.data.masterTokenInfo);
          let date = {
            accessToken: res.data.masterTokenInfo,
            cv: 'webgl_threejs@1.0',
            bodyId: 'nh_webreal_female_01',
            picture: this.uploadUrl,
            saasModeling: true,
          };
          this.$Request.postH("/open/srv/avatar/createWithPicture", date).then((res) => {
            console.log(res);
          });
          // console.log('After await');
          // this.loading = false;
        }
      });
      console.log('makeNewAvatar:' + uni.getStorageSync('makeNewAvatar'))
    },
    onChangeSex(e) {
      this.makeNewAvatar.sex = this.sexList[e.detail.value];
    },
    onChangeTimbre(e) {
      this.makeNewAvatar.timbre = this.timbre[e.detail.value].type;
      this.makeNewAvatar.timbreName = this.timbre[e.detail.value].name;
    },
    onChangeRole(e) {
      this.makeNewAvatar.role = this.role[e.detail.value];
      this.makeNewAvatar.roleName = this.roleList[e.detail.value];
    },
    // 切换模式
    modeSwitch(index) {
      this.currentModeIndex = index + 1
      this.showPassword = false
    },
    /**粒子进行*/
    gameloop() {
      this.timer = setTimeout(this.gameloop, 100);
      // console.log('gameloop')
      this.paint();
    },
    /**清空画布*/
    paint() {
      this.ctx.clearRect(0, 0, w, h)
      for (var i = 0; i < this.points.length; i++) {
        this.points[i].move(w, h)
        this.points[i].draw(this.ctx)
        for (var j = i + 1; j < this.points.length; j++) {
          this.points[i].drawLine(this.ctx, this.points[j])
        }
      }
      this.ctx.draw();
    },
    // 手动上传文件
    upload() {
      this.$refs.imageUpload.upload()
    },
    // 手动清空列表
    clear() {
      this.$refs.imageUpload.clear()
    },
	// 开始录音
	startVoice(){
			  console.log('开始录音')
			  this.showVoice = true
			  // this.recorderManager.start()
			  // const recorderManager = uni.getRecorderManager()
			  const options = {
					//采样率
					sampleRate: 24000,
					//录音通道数
					numberOfChannels: 1,
					//编码码率
					encodeBitRate: 16,
					//音频格式
					format: 'pcm'
			}
			  recorderManager.start(options)
			  // this.record.start().then(() => {
			  //   this.recording = true;
			  // });
	},
	// 结束录音
	endVoice(){
			console.log('结束录音')
		this.showVoice = false
			// const recorderManager = uni.getRecorderManager()
		recorderManager.stop()
			// this.record.stopToText({ model: "16k_zh" }).then((text) => {
			//     console.log(text);
			//   }).finally(() => {
			//     this.recording = false;
			//   });
	},
  }
}
</script>

<style lang="scss" scoped>
.input-box {
  background-color: #282a2e;
  margin: 15px 17px;
  border-radius: 15px;
  padding: 15px 0;

  .tn-text {
    padding: 5px 10px 0px 15px;
    color: #FFFFFF;
    font-size: 16px;
  }

  .tn-text1 {
    padding: 5px;
    color: #FFFFFF;
    font-size: 16px;
  }

  .tn-bg-gray--light {
    background-color: #3c3d3e !important;
  }

  .input-placeholder {
    font-size: 13px;
    color: #C6D1D8;
  }

  .topic__info__item__input {
    color: #fff;
    padding-left: 10px;
  }

  .topic__info__item__input {
    margin-top: 15px;
    margin-bottom: 15px;
  }

  .select-content {
    display: flex;
    align-items: center;
    margin-top: 10px;

    .select-content-item {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      width: 72px;
      height: 35px;
      border-radius: 24px;
      border: 0.5px solid #ccc;
      margin-right: 10px;
    }

    .select-content-item-active {
      border: 1px solid #EDC454;
      color: #EDC454;
    }
  }


}

.input-box-padding {
  padding: 15px 10px;
}

.bottom-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background-color: #1c1d20;
}

/* 胶囊*/
.tn-custom-nav-bar__back {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  box-sizing: border-box;
  background-color: rgba(0, 0, 0, 0.15);
  border-radius: 1000rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.5);
  color: #FFFFFF;
  font-size: 18px;

  .icon {
    display: block;
    flex: 1;
    margin: auto;
    text-align: center;
  }

  &:before {
    content: " ";
    width: 1rpx;
    height: 110%;
    position: absolute;
    top: 22.5%;
    left: 0;
    right: 0;
    margin: auto;
    transform: scale(0.5);
    transform-origin: 0 0;
    pointer-events: none;
    box-sizing: border-box;
    opacity: 0.7;
    background-color: #FFFFFF;
  }
}

/* 粒子背景 start*/
.template-topic {
  background: linear-gradient(90deg, #1c1d21, #1c1d21);
  min-height: 100vh
}

.mycanvas {
  position: fixed;
  background-size: cover;
  width: 100vw;
  height: 100vh;
  justify-content: center;
  flex-direction: column;
  color: #fff;
}



.topic {
  position: relative;
  height: 100%;
  z-index: 1;
  margin-bottom: 120rpx;


  /* 表单信息 start */
  &__info {
    margin: 105rpx 50rpx 0rpx 50rpx;
    padding: 30rpx 50rpx 50rpx 50rpx;
    border-radius: 20rpx;
    background-color: rgba(255, 255, 255, 1);
    border: 2rpx solid rgba(255, 255, 255, 0.1);
    box-shadow: 0rpx 10rpx 50rpx 0rpx rgba(0, 3, 72, 0.1);

    &__item {

      &__input {
        margin-top: 59rpx;
        width: 100%;
        height: 77rpx;
        border: 1rpx solid #C6D1D8;
        border-radius: 39rpx;

        &__left-icon {
          width: 10%;
          font-size: 44rpx;
          margin-left: 20rpx;
          color: #78909C;
        }

        &__content {
          width: 80%;
          padding-left: 10rpx;

          &--verify-code {
            width: 56%;
          }

          input {
            font-size: 30rpx;
            color: #78909C;
            // letter-spacing: 0.1em;
          }
        }

        &__right-icon {
          width: 10%;
          font-size: 34rpx;
          margin-right: 20rpx;
          color: #78909C;
        }

        &__right-verify-code {
          width: 34%;
          margin-right: 20rpx;
        }
      }

      &__button {
        margin-top: 59rpx;
        width: 100%;
        height: 77rpx;
        text-align: center;
        font-size: 31rpx;
        font-weight: bold;
        line-height: 77rpx;
        // text-indent: 1em;
        border-radius: 100rpx;
        color: #FFFFFF;
        background-color: rgba(255, 255, 255, 0.2);
        // border: 2rpx solid #FFFFFF;
      }

      &__sure {
        margin-top: 75rpx;
        margin-bottom: 39rpx;
        width: 100%;
        letter-spacing: 0.5em;
      }

    }
  }

  /* 表单信息 end */

  /* 内容 end */

}

::v-deep.input-placeholder {
  font-size: 30rpx;
  color: #C6D1D8;
}
</style>
